<?php

namespace App\Models\Traits;

trait HasTreeStructure
{
    /**
     * 获取树形结构
     *
     * @param int $parentId
     * @param array $conditions 额外的查询条件
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function tree($parentId = 0, array $conditions = [])
    {
        $query = static::where('parent_id', $parentId);
        
        // 如果有状态字段，默认只查询启用的
        if (in_array('status', (new static)->getFillable())) {
            if (isset($conditions['status'])) {
                $query->where('status', $conditions['status']);
            }
        }
        
        // 处理类型过滤（支持数组，用于排除按钮类型）
        if (isset($conditions['type'])) {
            if (is_array($conditions['type'])) {
                $query->whereIn('type', $conditions['type']);
            } else {
                $query->where('type', $conditions['type']);
            }
        }
        
        // 应用其他额外的查询条件
        foreach ($conditions as $key => $value) {
            if (!in_array($key, ['status', 'type']) && in_array($key, (new static)->getFillable())) {
                $query->where($key, $value);
            }
        }
        
        return $query->orderBy('sort')
            ->orderBy('id')
            ->get()
            ->map(function ($item) use ($conditions) {
                $children = static::tree($item->id, $conditions);
                // 使用setRelation设置children，这样MenuResource可以通过relationLoaded检查
                $item->setRelation('children', $children);
                return $item;
            });
    }

    /**
     * 获取所有子节点ID（包括自己）
     *
     * @param int $id
     * @return array
     */
    public static function getChildrenIds($id): array
    {
        $ids = [$id];
        $children = static::where('parent_id', $id)->pluck('id')->toArray();
        
        foreach ($children as $childId) {
            $ids = array_merge($ids, static::getChildrenIds($childId));
        }
        
        return $ids;
    }

    /**
     * 检查是否有子节点
     *
     * @param int $id
     * @return bool
     */
    public static function hasChildren($id): bool
    {
        return static::where('parent_id', $id)->exists();
    }
}

